import csv
from datetime import datetime


def check_csv_file(file_path, signal_emitter, delimiter=','):
    try:
        with open(file_path, 'r', encoding='utf-8') as csvfile:
            reader = csv.reader(csvfile, delimiter=delimiter)
            header = next(reader)  # 获取第一行（表头），同时也将文件读取指针移到下一行
            expected_columns_number = len(header)
            row_index = 1  # 从第二行开始计数（因为第一行已经获取作为表头了）
            signal_emitter.result_signal.emit(False,
                                              f"INFO    {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}   "
                                              f"Start checking, Delimiter is “{delimiter}”    "
                                              f"expected_columns_number is {expected_columns_number}", None)
            for row in reader:
                if len(row) != expected_columns_number:
                    signal_emitter.result_signal.emit(False,
                                                      f"ERROR    {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}    Maybe {row_index + 1} row broken",
                                                      None)
                row_index += 1
            signal_emitter.result_signal.emit(False, f"INFO    {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}    Done",
                                              None)
    except csv.Error as e:
        signal_emitter.result_signal.emit(False,
                                          f"ERROR    {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}    Error parsing CSV: \n{e}",
                                          None)